package application.adapter;

import application.anno.Layout;
import application.exception.NotFoundNecessaryAnnotationException;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import lombok.Getter;

import java.io.IOException;
import java.util.List;

public class ListAdapter<T> {

    @Getter
    private volatile List<T> items;

    private ListView<Pane> listView;

    private String layout;

    private ItemOnClickListener itemOnClickListener = new ItemOnClickListener() {
        @Override
        public void itemOnClickListener() {

        }
    };

    public ListAdapter(ListView<Pane> listView, String layout) {
        this.listView = listView;
        this.layout = layout;
    }

    public void setItems(List<T> items) {
        listView.getItems().clear();
        this.items = items;
        if (items == null || items.isEmpty()) {
            return;
        }
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < items.size(); i++) {
                    try {
                        Pane view = getView(i);
                        listView.getItems().add(view);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    protected Pane getView(int index) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(this.getClass().getClassLoader().getResource("layout/".concat(layout)));
        Pane pane = fxmlLoader.load();
        ListViewController listViewController = fxmlLoader.getController();
        listViewController.initialize(items.get(index));
        pane.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                itemOnClickListener.itemOnClickListener();
            }
        });
        return pane;
    }

    public interface ListViewController<T> {
        void initialize(T t);
    }

    public interface ItemOnClickListener {
        void itemOnClickListener();
    }

}
